<?php
$mosaic_photo_url = "http://farm3.static.flickr.com/2013/2323692352_f3c546b64a_b.jpg?v=1205206190"; //jon.jpg"; 
$mosaic_photo_url = 'http://farm4.static.flickr.com/3033/2322004873_4d57aa3d1d_b.jpg?v=1205173557';
$mosaic_photo_url = 'http://orz.4chan.org/hr/src/1205021696681.jpg';
?>
<script>
var zindex = 10000;
window.onload = function () {
	var imgs = document.getElementsByTagName('img');
	for (var i = 1; i < imgs.length; i++) {
		imgs[i].onmouseover = hoverImg;
		imgs[i].onmouseout = unhoverImg;
	}
}
function hoverImg() {
	this.className = 'large';
	this.style.zIndex = zindex++;
	//document.getElementById('overlay').style.zIndex = (zindex++);
}
function unhoverImg() {
	this.className = 'small';
}
</script>
<style>
body { background: url(<?php echo $mosaic_photo_url; ?>) top left no-repeat; padding: 0; margin: 0; }
img.large {
	position:	absolute;
}
.small img {
	width:	16px;
	height:	16px;
	opacity:	.75;
	filter:		alpha(opacity=75);
}
img.large {
	width:	150px;
	height:	150px;
	margin-left: -75px;
	margin-top: -75px;
	border: solid 1px #ccc;
	padding: 2px;
	background-color: #fff;
}
</style>
<?php
require_once 'database.php';
set_time_limit(0);

mysql_connect('localhost', 'root', '');
mysql_select_db('photosaic');
mysql_query("truncate table photo_cache2");
$r= 16;
mysql_query("insert into photo_cache2 (photo_id, url, r, g, b) select photo_id, url, round(r/$r)*$r, round(g/$r)*$r, round(b/$r)*$r from photo_cache");

function getColorOfCell($img, $x,$y,$w,$h) {
	$return = array(0,0,0); $ct = 0;
	for ($i = $x; $i < $x+$w; $i++) {
		for ($j = $y; $j < $y+$h; $j++) {
			if ($i < imagesx($img) && $j < imagesy($img)) {
				$rgb = imagecolorsforindex($img, imagecolorat($img, $i, $j));		
				$return[0] += $rgb['red'];
				$return[1] += $rgb['green'];
				$return[2] += $rgb['blue'];
				$ct++;
			}
		}
	}
	return array('r' => round($return[0] / $ct), 'g' => round($return[1] / $ct), 'b' => round($return[2] / $ct));
}

$cellWidth = 16;
$cellHeight = 16;

$db = new Database();

$img = imagecreatefromjpeg($mosaic_photo_url);
echo	"<div class='small' style='width: ".(ceil(imagesx($img)/16.0)*16)."px'>";
for ($y = 0; $y < imagesy($img) / $cellHeight; $y++) {
	for ($x = 0; $x < imagesx($img) / $cellWidth; $x++) {
		$rgb = getColorOfCell($img, $x * $cellWidth, $y * $cellHeight, $cellWidth, $cellHeight);
		$result = mysql_query("select photo_id, url from photo_cache2 order by (abs(r-'$rgb[r]')+abs(g-'$rgb[g]')+abs(b-'$rgb[b]')), last_used limit ".rand(0,2).", 1");
		while ($photo = mysql_fetch_array($result)) {
			// $photo_path = $photo['url'];
			$photo_path = "photos/$photo[photo_id].jpg";
			//echo	"<img src='$photo_path' style='left:".($x*$cellWidth).";top:".($y*$cellHeight)."'/>";
echo	"<img src='$photo_path'/>";
			//mysql_query("update photo_cache2 set last_used=now() where photo_id='$pic[photo_id]'");
		}

	}echo "<br/>";
}
echo	"</div>";


?>